<template>
  <div class="el-main">
    <el-main>
      <div class="cart-icon-container" @click="toggleCart">
       <img src="../assets/img/购物车.jpg"/>
        <div class="cart-count">{{ cart.length }}</div>
      </div>
      <div class="main-content">
        <h1></h1>
        <div class="greeting">
          <p>欢迎您!祝您今天过得开心!</p>
        </div>
        <div class="tables-info">
          <div v-for="good in goods" :key="good.id" class="table-item">
            <img :src="good.mealPicture" alt="菜品图片" class="table-image" />
            <div class="table-details">
              <p>菜 名：{{ good.mealName }}</p>
              <p>类 型：{{ good.mealType }}</p>
              <p>单 价：{{ good.price }}/份</p>
              <p>描 述：{{ good.description }}</p>

              <el-button
                type="warning"
                v-if="good.statusd !== '占用'"
                @click="orderMeal(good)"
              >
                <i class="el-icon-shopping-cart-2"></i>加 1
              </el-button>
              <el-button
                type="warning"
                v-if="good.statusd !== '占用'"
                @click="collectMeal(good.id, good.mealName)"
              >
                <i class="el-icon-star-off"></i>收 藏
              </el-button>
            </div>
          </div>
        </div>
        <div class="cart" v-if="isCartVisible">
          <h2>购物车</h2>
          <ul>
            <li v-for="(item, index) in cart" :key="index">
              {{ item.mealName }} - {{ item.price }}元 x {{ item.quantity }}
              <button @click="increaseQuantity(index)">+</button>
              <button @click="decreaseQuantity(index)">-</button>
              <button @click="removeFromCart(index)">删除</button>
            </li>
          </ul>
          <button @click="settleAccounts">结算</button>
          <button @click="clearCart">清空购物车</button>
          <button @click="isCartVisible = false">关闭购物车</button>
        </div>
      </div>
    </el-main>
  </div>
</template>
<script>
export default {
  data() {
    return {
      userInfo: {
        userId: null,
        userName: "",
      },
      goods: [],
      cart: [],
      isCartVisible: false, // 控制购物车列表的显示
    };
  },
  mounted: function () {
    this.getMealData();
    this.userInfo = JSON.parse(localStorage.getItem('user'));
  },
  methods: {

    async collectMeal(goodId, goodName) {
    try {
      // 构造请求的数据
      const requestData = {
        userId: this.userInfo.id,
        userName: this.userInfo.userName,
        goodsId: goodId,
        goodsName: goodName
      };

      // 发送请求到后端API
      const response = await this.$http.post('/shoucanglan/addToS', requestData);
      if (response.status === 200 ) {
        // 根据后端的响应来处理结果
        this.$message.success("收藏成功")
        console.log('收藏成功', response.data);
        // 这里可以添加一些用户反馈，例如提示信息
      } else {
        this.$message.error("收藏失败")
        console.error("收藏失败:", response.data);
      }
    } catch (error) {
      this.$message.error("收藏失败")
      console.error("请求添加收藏数据失败:", error);
    }
  },
    async getMealData() {
      try {
        const response = await this.$http.get("/goods/getAllGoods");
        this.goods = response.data;
      } catch (error) {
        console.error(error);
      }
    },

    orderMeal(good) {
      const existingItem = this.cart.find((item) => item.id === good.id);
      if (existingItem) {
        // 如果商品已存在，增加其数量
        existingItem.quantity += 1;
      } else {
        // 如果商品不存在，添加到购物车
        this.cart.push({ ...good, quantity: 1 });
      }
      this.$message.success("商品已加入购物车");
    },

    removeFromCart(index) {
      this.cart.splice(index, 1);
      this.$message.success("商品已从购物车移除");
    },

    clearCart() {
      this.cart = [];
      this.$message.success("购物车已清空");
    },

    toggleCart() {
      this.isCartVisible = !this.isCartVisible;
    },

    settleAccounts() {
      const total = this.cart.reduce(
        (acc, item) => acc + item.price * item.quantity,
        0
      );
      this.$message.success(`结算成功，总价为：${total}元`);

      this.cart = [];
    },
    increaseQuantity(index) {
      this.cart[index].quantity += 1;
    },

    decreaseQuantity(index) {
      if (this.cart[index].quantity > 1) {
        this.cart[index].quantity -= 1;
      } else {
        this.removeFromCart(index);
      }
    },
  },
};
</script>


<style scoped>
/*背景图 */
.el-main {
  background-image: url('../assets/img/main.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed; /* 固定背景图像 */
  padding: 20px;
}
.cart-dialog button {
  margin: 10px;
  padding: 10px 20px;
  background-color: #f27c0d;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.cart-dialog button:hover {
  opacity: 0.9;
}
/*图标 */
.table-image {
  width: 100px; /* 或者使用 max-width 来适应不同屏幕尺寸 */
  height: 80px;
  display: block; /* 使图片宽度不会超过其容器宽度 */
  margin: 0 auto; /* 居中显示图片 */
}

.main-content {
  text-align: center;
}

/*欢迎您字段 */
.greeting p {
  font-size: 30px;
  margin: 10px 0;
  color: #d1f62a;
}

/*每个座位 */
.tables-info {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 项目向左对齐 */
  margin-top: 20px;
  font-size: 13px;
  gap: 10px;
}

/*与右边间隔 */
.table-item {
  margin-right: 160px;
}

.table-item:last-child {
  margin-right: 0; /* 重置最后一个项目的右边距 */
}

/*座位字段 */
.table-details {
  color: #99b9e1;
  font-size: 13px;
  gap: 10px;
}

.table-details button {
  background-color: #f27c0d !important; /* 按钮的初始颜色 */
  padding: 10px 20px; /* 设置按钮的内边距，使按钮内部内容与边界有更多空间 */
  font-size: 14px; /* 设置按钮文本的大小 */
  line-height: 1; /* 确保文本高度与按钮高度一致 */
  border-radius: 5px; /* 设置按钮的圆角大小 */
  cursor: pointer; /* 鼠标悬停在按钮上时显示手形图标 */
  width: 60px; /* 设置按钮的宽度 */
  height: 60px; /* 设置按钮的高度 */
  font-size: 10px; /* 设置按钮文本的大小 */
}

.el-breadcrumb button {
  color: #65fa09; /* 文字的初始颜色 */
  border: none; /* 去掉边框 */
  background-color: transparent; /* 去掉背景色 */
  font-size: 20px; /* 文字的字体大小 */
  cursor: pointer; /* ��标���停在文字上时显示手形图标 */
}
.cart {
  margin-top: 20px;
}

.cart ul {
  list-style-type: none;
  padding: 0;
}

.cart li {
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.cart li:last-child {
  border-bottom: none;
}

.cart-count {
  position: absolute;
  bottom: 200px;
  right: 155px;
  background-color: #f27c0d;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}
.cart-icon-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  cursor: pointer;
  font-size: 24px;
  color: #f27c0d;
}

.cart-list {
  position: fixed;
  bottom: 60px;
  right: 20px;
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  width: 300px;
}

.cart-dialog {
  border: none;
}
.cart-icon-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  cursor: pointer;
  font-size: 24px;
  color: #f27c0d;
}

.cart-count {
  position: absolute;
  bottom: 10px;
  right: 15px;
  background-color: #f27c0d;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.cart {
  position: fixed;
  bottom: 60px;
  right: 20px;
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  width: 300px;
  z-index: 1000; /* 确保购物车在其他元素之上 */
}

.cart h2 {
  margin-bottom: 10px;
}

.cart ul {
  list-style-type: none;
  padding: 0;
}

.cart li {
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.cart li:last-child {
  border-bottom: none;
}

.cart button {
  margin: 10px 5px;
  padding: 10px 20px;
  background-color: #f27c0d;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.cart button:hover {
  opacity: 0.9;
}
/* 其他样式 */
</style>